<template>
  <view class="page">
    <cl-nav-bar></cl-nav-bar>
    <view class="page_search">
      <uni-search-bar
        v-model.trim="keyword"
        cancelButton="none"
        radius="30"
        placeholder="请输入关键字查询"
      >
      </uni-search-bar>
    </view>
    <view class="page_content" v-if="filterTempalteList.length > 0">
      <view
        v-for="item in filterTempalteList"
        :key="item.templateId"
        class="template_item"
        @click="handleToTemplateOrFill(item)"
      >
        <image
          src="../../static/template_icon.png"
          class="template_item_icon"
          mode="scaleToFill"
        />
        <view v-html="highlightKeywords(item.name)" class="exceed_omit1"></view>
        <image
          v-if="pageType === 'template'"
          src="../../static/del_icon.png"
          class="del_icon"
          mode="scaleToFill"
          @click.stop="handleDel(item)"
        />
      </view>
    </view>
    <empty v-else></empty>
    <view class="g_bottom_box" v-if="pageType === 'template'">
      <view class="g_bottom_box_btn" @click="handleToAddOrEdit()">
        新增模板
      </view>
    </view>
  </view>
</template>

<script setup>
import { getOrCreateDir, getDirList, removeDir } from '../../utils/file'
import { onLoad } from '@dcloudio/uni-app'

const templateList = ref([])
// 页面类型  template模板类型 fill填充类型
const pageType = ref('tempalte')
onLoad(async (options) => {
  if (options.pageType) {
    pageType.value = options.pageType
  }
  await getOrCreateDir('_doc/templateList', true)
  // 进入模板列表则直获取模板数据，没有则直接创建
  getTemplateList()
})
const keyword = ref('')
// 过滤列表
const filterTempalteList = computed(() => {
  return templateList.value.filter((item) => item.name.includes(keyword.value))
})
// 高亮展示
const highlightKeywords = (name) => {
  if (keyword.value.length === 0) {
    return `<span>${name}</span>`
  }
  const reg = new RegExp(keyword.value, 'g')
  return name.replace(reg, `<span style="color: red">${keyword.value}</span>`)
}

// 跳转模板还是填充
const handleToTemplateOrFill = (data) => {
  if (pageType.value === 'fill') {
    uni.navigateTo({ url: '/pages/fill/list?dirName=' + data.dirName })
  } else {
    handleToAddOrEdit(data)
  }
}

// 删除
const handleDel = (data) => {
  uni.showModal({
    title: '提示',
    content: '删除模板，对应填报数据也会删除，确认删除？',
    showCancel: true,
    success: async ({ confirm, cancel }) => {
      if (confirm) {
        await removeDir(`_doc/templateList/${data.templateId}_${data.name}`)
        uni.showToast({
          title: '删除成功！',
          duration: 500,
          success: () => {
            getTemplateList()
          },
        })
      }
    },
  })
}

// 去新增或者修改
const handleToAddOrEdit = (data) => {
  uni.navigateTo({
    url: '/pages/template/edit',
    events: {
      acceptDataFromOpenedPage: () => {
        getTemplateList()
      },
    },
    success: async (res) => {
      // 通过eventChannel向被打开页面传送数据
      res.eventChannel.emit('acceptDataFromOpenerPage', data?.dirName)
    },
  })
}

const getTemplateList = async () => {
  uni.showLoading({ title: '数据加载中' })
  const dirList = await getDirList('_doc/templateList')
  templateList.value = dirList.map((dirName) => {
    const idx = dirName.indexOf('_')
    if (idx !== -1) {
      return {
        name: dirName.slice(idx + 1),
        templateId: dirName.slice(0, idx),
        dirName,
      }
    } else {
      return {
        name: '错误数据，请排除',
      }
    }
  })
  setTimeout(() => {
    uni.hideLoading()
  }, 500)
}
</script>

<style lang="scss" scoped>
.page {
  display: flex;
  flex-direction: column;
  height: 100%;
  &_search {
    background-color: #fff;
  }
  &_content {
    margin-top: 20rpx;
    flex: 1;
    .template_item {
      margin-bottom: 4rpx;
      padding: 28rpx;
      display: flex;
      align-items: center;
      background-color: #fff;
      &_icon {
        margin-right: 40rpx;
        flex-shrink: 0;
        width: 50rpx;
        height: 50rpx;
      }
      .del_icon {
        margin-left: auto;
        width: 50rpx;
        height: 50rpx;
      }
    }
  }
}
</style>
